<?php
namespace Kxdr\Controller;
use Think\Controller;
class GamesetController extends ExtendController {
		public function save_edit(){
			$field = I("field");
			$id = I("id");
			$value = I("value");
			switch($field){
				case "event_title":
					$db = "KxdrEvents";
					$data=Array("title"=>$value);
				break;
				case "event_descrip":
					$db = "KxdrEvents";
					$data=Array("description"=>$value);
				break;
				case "game_name":
					$db = "KxdrGames";
					$data=Array("name"=>$value);
				break;
				case "start_time":
					$db = "KxdrGames";
					$data=Array("start_time"=>$value);
				break;
				case "location":
					$db = "KxdrGames";
					$data=Array("location"=>$value);
				break;
				case "game_descrip":
					$db = "KxdrGames";
					$data=Array("description"=>$value);
				break;
				case "player_name":
					$db = "KxdrPlayers";
					$data=Array("chinese_name"=>$value);
				break;
				case "event_player_descrip":
					$db = "KxdrEvents";
					$data=Array("player_descrip"=>$value);
				break;
				case "player_descrip":
					$db = "KxdrPlayers";
					$data=Array("description"=>$value);
				break;
				case "think_type":
					$way = I("way");
					$db = "KxdrEvents";
					$data=Array("think_type"=>$value,"think_type_way"=>$way);
				break;
				case "gifting_time":
					$db = "KxdrEvents";
					$data=Array("gifting_time"=>$value);
				break;
				case "gift_cffs":
					$db = "KxdrEvents";
					$data=Array("think_type"=>$value);
					
				break;
				// case "gift_name":
					// $db = "Gifts";
					// $data=Array("name"=>$value);
				// break;
				case "gift_event_quant":
					$db = "KxdrEventGifts";
					$data=Array("quantity"=>$value);
				break;
				case "gift_hqfs":
					$db = "KxdrEventGifts";
					$data=Array("get_type"=>$value);
				break;
				// case "gift_price":
					// $db = "Gifts";
					// $data=Array("price"=>$value);
				// break;
			}
			$DBT = M($db);
			$re = $DBT->where("`id`=".$id." AND `sid`=".$this->sid)->save($data);
			$this->ajaxReturn(Array("status"=>$re));
		}
		public function get_gifts(){
			$GIFT = M("Gifts");
			$gifts = $GIFT->where("`status`=0 AND `sid`=".$this->sid)->getField("`name` AS `text`,`name`,`id` AS `value`,`quantity`,`pic_url`,`id`,`type`",true,true);
			foreach($gifts as $k=>$g){
					$gifts[$k]["text"].="（".$g["quantity"]."）";
			}
			$gifts = array_values($gifts);
			$this->ajaxReturn($gifts);
		}

		public function loadgames(){
			$id = I("id")?I("id"):0;
			$GAME = M("KxdrGames");
			//第一次预备上线时，只提供足球  game_category="football"
			$games = $GAME->where("`fid`=$id AND (`sid`=".$this->sid." OR `sid`=0) AND (`start_time` IS NULL OR `start_time`>='".date("Y-m-d H:i:s")."') AND `version`= '".session("app_version")."'")->getField("`name` AS `text`,`id`,`fid`,`is_leaf` AS `leaf`,date_format(`start_time`,'%Y-%m-%d %H:%i:%s') AS `start_time`,`description`,`pic_url`,`game_category`,CASE `team_type` WHEN 'team' THEN (`fid`) ELSE (`id`) END  AS `privat_league_id`,CASE `team_type` WHEN 'league' THEN (`name`) END  AS `league_name`,`game_category`,`team_type`",true,true);
			// echo $GAME->_sql();
			if(!$games){
				$reda["hasError"]=true;
				$reda["error"]=L("EVENT_STEP1_TIP_NO_EVENT");
				$this->ajaxReturn($reda);
				die();
			}
			// echo $GAME->_sql();
			foreach($games as $k=>$g){
				$games[$k]["leaf"]=$games[$k]["leaf"]?true:false;
				$games[$k]["text"].=$games[$k]["start_time"]?"(".date("m月d日",strtotime($games[$k]["start_time"])).")":"";
				if(!$g["leaf"]){
					$games[$k]["cls"]="x-tree-icon x-tree-elbow-dir";
					if($g["sid"]){
						$games[$k]["cls"]="x-tree-icon x-tree-elbow-dir"; //自定义类目特殊标识
					}
				}
			}
			$reda = array_values($games);
			$this->ajaxReturn($reda);
		}
		public function loadplayers(){
			$id = I("id");
			$game_id = I("game_id")?I("game_id"):session("game_id");
			if(!$game_id){
				$reda["hasError"]=true;
				$reda["error"]=L("EVENT_STEP2_TIP_GAMEID_ERR");
				$this->ajaxReturn($reda);
				die();
			}
			
			$PLAYER = M("KxdrPlayers");
			$GAME = M("KxdrGames");
			$game = current($GAME->where("`id`=$game_id")->getField("`id`,`game_category`,`is_leaf`,`team_type`,`outside_id`"));
			$where_player = "(`sid`='".$this->sid."' OR `is_pub`='1')";
			if(!$id){
				// 没有id表示读取比赛的所有参赛队员，分以下3种情况，所有比赛类别下的队伍，联赛内比赛的队伍，本场比赛参赛队伍
				if($game["team_type"]=="league"){
					$where_player .= " AND `privat_league_id`='".$game["id"]."' AND `is_team`='1'";
				}
				
				if($game["team_type"]=="cat"){
					$where_player .= " AND `game_category`='".$game["game_category"]."'";
				}
				
				if($game["team_type"]=="match" ){
					if($game["game_category"]=="football"){
						$Teamscore = M("KxdrGamesSoccerTeamscore");
						$player_ids = current($Teamscore->where("`game_id`='$game_id'")->getField("id,private_home_team_id,private_guest_team_id"));
						unset($player_ids["id"]);
						$player_ids = implode(",",$player_ids);
					}
					$where_player .= " AND `id` IN (".($player_ids?$player_ids:0).")";
				}
			}else{
				$where_player.=" AND `private_team_id`='".$id."'";
			}
			$players = $PLAYER->where($where_player)->getField("`chinese_name` AS `text`,`id`,`team_id` AS `fid`,`is_team` AS `leaf`,`description`,`game_category`,`private_league_id`,`league_id`,`league_name`",true,true);

			if(!$players){
				$reda["hasError"]=true;
				if(!I("fid")){
					$reda["error"]=L("EVENT_STEP2_TIP_NOTEAMS");
				}else{
					$reda["error"]=L("EVENT_STEP2_TIP_NOPLYAERS");
				}
				$this->ajaxReturn($reda);
				die();
			}
			foreach($players as $k=>$g){
				$players[$k]["leaf"]=$players[$k]["leaf"]?false:true;
				if(!$g["leaf"]){
					$players[$k]["cls"]=" icon-user";
					if($g["sid"]){
						$players[$k]["cls"]="x-tree-icon x-tree-elbow-dir"; //自定义类目特殊标识
					}
				}else{
					// 队员标志
					$players[$k]["cls"]="icon-map-marker";
				}
			}
			// echo $PLAYER->_sql();
			$reda = array_values($players);
			// $reda["hasError"]=true;
			// $reda["error"]="没有任何队员哦！请添加。";
			$this->ajaxReturn($reda);
		}
		public function add_event_player(){
			$title = I("title");
			$player_id = I("player_id");
			$cffs = I("cffs");
			$cffsval = I("cffsval");
			$zmc = I("zmc");
			$player_descrip = I("player_descrip");
			$player_name = I("player_name");
			$target_data = I("target_data");
			$target_data_sign = I("target_data_sign");
			$target_data_very = I("target_data_very");
			$event_id = session("event_id");
			
			$GAME = M("KxdrEventPlayers");
			if($event_id){
				$data["event_id"]=$event_id;
				$data["player_id"]=$player_id;
				$data["title"]=$title;
				$data["player_descrip"]=$player_descrip;
				$data["think_type"]=$cffs;
				$data["think_type_sign"]=$cffsval;
				$data["think_type_way"]=$zmc;
				$data["target_data"]=$target_data;
					if($target_data_very){
						$target_data_sign++;
						// 前端传回0，或者2。包含当前值，则自增，如下：
						// 0：正向预测不含当前值
						// 1：正向预测含当前值
						// 2：负向预测不含当前值
						// 3：负向预测含当前值
					}
				$data["target_data_sign"]=$target_data_sign;
				$data["sid"]=$this->sid;
				$data["epid"]=$GAME->add($data);
				if(!$data["epid"]){
					$data["isError"]=true;
					$data["error"]=L("EVENT_STEP2_TIP_ADDPLR_ERR");
				}else{
					$data["player_name"]=$player_name;
					foreach(C("KXDR_THINK_WAY") as $way){
						if($data["think_type_way"]==$way["id"]){
							$data["think_type_way_name"]=$way["name"];break;
						}
					}
					$players = session("players");
					$players[$data["epid"]]=$data;
					session("players",$players);
				}
			}else{
				$data["isError"]=true;
				$data["error"]=L("EVENT_STEP2_TIP_ADDPLR_ERR_NOEVT");
			}
			$this->ajaxReturn($data);
		}
		public function del_event_palyer(){
			$id = I("epid");
			$PLR = M("KxdrEventPlayers");
			$re = $PLR->where("`id`=".$id." AND `sid`=".$this->sid)->delete();
			if($re){
				$GUESS = M("KxdrUserGuess");
				$GUESS->where("`epid`=".$id." AND `sid`=".$this->sid)->delete(); //已经预测的用户数据删除
				//奖品也要删掉。。。
				$players = session("players");
				unset($players[$id]);
				session("players",$players);
			}
			$this->ajaxReturn(Array("status"=>$re));
		} 
		public function edit_game(){
			$id = I("id");
			$fid = I("fid");
			$name = I("name");
			$action = I("action");
			$game_category = I("game_category");
			$team_type = I("team_type");
			$GAME = M("KxdrGames");
			if($action=="add"){
				$data["is_leaf"]=$team_type=="team"||$team_type=="league"?true:false;
				$data["fid"]=$fid;
				if($team_type=="cat"){
					$data["team_type"]="league";
				}
				if($team_type=="league"){
					$data["team_type"]="match";
				}
				$data["name"]=$name;
				$data["short_name"]=$name;
				$data["sid"]=$this->sid;
				$data["is_pub"]=false;
				$data["edit_time"]=date("Y-m-d H:i:s",time());
				$data["game_category"]=$game_category;
				$data["version"]=session("app_version");
				$data["id"]=$GAME->add($data);
			}else{
				$data["name"]=$name;
				$GAME->where("`id`=".$id." AND `sid`=".$this->sid)->save($data);
			}
			$data["err"]=$GAME->getDbError();
			$this->ajaxReturn($data);
		}
		public function edit_player(){
			$game_id = I("game_id")?I("game_id"):session("game_id");
			$name = I("name");
			$fid = I("fid");
			$id = I("id");
			$action = I("action");
			$game_category = I("game_category");
			$privat_league_id = I("privat_league_id");
			$league_id = I("league_id");
			$league_name = I("league_name");
			$GAME = M("KxdrPlayers");
			if($action=="add"){
				$data["is_team"]=$fid?false:true;
				$data["team_id"]=$fid;
				$data["chinese_name"]=$name;
				$data["sid"]=$this->sid;
				$data["version"]=session("app_version");
				$data["game_category"]=$game_category;
				$data["private_league_id"]=$privat_league_id;
				$data["league_id"]=$league_id;
				$data["league_name"]=$league_name;
				$data["id"]=$GAME->add($data);
				if($game_category=="football" && $data["is_team"]){  //&& $data["is_team"]
					// 添加足球比分数据
					$db = M("KxdrGamesSoccerTeamscore");
					$score = ($db->where("`game_id`=".$game_id)->getField("`id`,`private_home_team_id`,`private_guest_team_id`"));

					if($score){
						$t["private_guest_team_id"]=$data["id"];
						$t["guest_team"]=$data["chinese_name"];
						$db->where("`game_id`=".$game_id)->save($t);
					}else{
						$tmp["game_id"]=$game_id;
						$tmp["private_home_team_id"]=$data["id"];
						$tmp["private_guest_team_id"]=0; 
						$tmp["outside_id"]=0;
						$tmp["match_id"]=0;
						$tmp["private_league_id"]=$privat_league_id;
						$tmp["league_id"]=0;
						$tmp["league_name"]=$league_name;
						$tmp["home_team"]=$data["chinese_name"];
						$tmp["home_team_id"]=0;
						$tmp["guest_team"]="";
						$tmp["guest_team_id"]=0;
						$tmp["gaming_time"]=date("Y-m-d 00:00:00");
						$tmp["status"]=17;
						// $tmp["game_url"]=
						$tmp["home_team_url"]="";
						$tmp["guest_team_url"]="";
						// $tmp["home_team_rank"]
						$tmp["home_team_score"]=0;
						$tmp["guest_team_score"]=0;
						$tmp["home_team_redcard"]=0;
						$tmp["guest_team_redcard"]=0;
						$tmp["home_team_yellowcard"]=0;
						$tmp["guest_team_yellowcard"]=0; 
						$tmp["home_team_halfscore"]=0;
						$tmp["guest_team_halfscore"]=0;
						$tmp["add_time"]=date("Y-m-d H:i:s");
				
				
						$db->add($tmp);
					}
					echo $db->getDbError();
				}
			}else{
				$data["chinese_name"]=$name;
				$GAME->where("`id`=".$id." AND `sid`=".$this->sid)->save($data);
				
			}
			
				$data["sql"]=$GAME->getDbError();
			$this->ajaxReturn($data);
		}
		public function del_player(){
			$id=I("id");
			$GAME = M("KxdrPlayers");
			if($this->sid){
				$data["status"] = $GAME->where("(`id`=".$id." AND `sid`=".$this->sid.") OR (`team_id`=$id AND `sid`=".$this->sid.")")->delete()?true:false;
			}
			if(!$data["status"]){
				$data["error"]=L("EVENT_STEP2_TIP_ADDPLR_DEL_ERR");
			}
			$this->ajaxReturn($data);
		}
		public function del_game(){
			$id=I("id");
			$GAME = M("KxdrGames");
			if($this->sid){
				$data["status"] = $GAME->where("(`id`=".$id." AND `sid`=".$this->sid.") OR (`fid`=$id AND `sid`=".$this->sid.")")->delete()?true:false;
			}
			if(!$data["status"]){
				$data["error"]=L("EVENT_STEP2_TIP_ADDPLR_DEL_ERR");
			}
			$this->ajaxReturn($data);
		}
		public function add_cffs(){
			$cffs = I("cffs");
			$data["sid"]=$this->sid;
			$data["name"]=$cffs;
			$data["app_version"]=session("app_version");
			$CFFS = M("KxdrCffs");
			$re = $CFFS->add($data);
			$this->ajaxReturn(Array("status"=>$re));
		}
		public function get_cffs(){
			$game_category = I("gcat");
			if($game_category=="football"){
				// $data[] = Array("text"=>'猜冠军(自动更新)',"value"=>'猜冠军');
				// $data[] = Array("text"=>'猜胜负(自动更新)',"value"=>'猜胜负');
				// $data[] = Array("text"=>'猜得分(自动更新)',"value"=>'猜得分');
				// $data[] = Array("text"=>'猜红牌(自动更新)',"value"=>'猜红牌');
				$data = C("CFFS_SOCCER_TEAM");
			}
			$CFFS = M("KxdrCffs");
			$cffs = $CFFS->where("`sid`=".$this->sid)->getField("`id`,`name`");
			foreach($cffs as $cf){
				$data[] = Array("text"=>$cf,"value"=>$cf);
			}
			$data[] = Array("text"=>'预测其他数据请添加',"value"=>'input');
			$this->ajaxReturn($data);
		}
		public function save_recom_items(){
			$numiid = I("numiid");
			$tjbt = I("tjbt");
			$tjnr = I("tjnr");
			$pic_url = I("pic_url");
			$data["event_id"]=session("event_id");
			$data["sid"]=$this->sid;
			$data["num_iid"]=$numiid;
			$data["title"]=$tjbt;
			$data["recomment"]=$tjnr;
			$data["pic_url"]=$pic_url;
			$RITEM = M("KxdrRecomItems");
			$re["status"] = $RITEM->add($data);
			$this->ajaxReturn($re);
		}
		public function remove_recom_item(){
			$numiid = I("numiid");
			$RITEM = M("KxdrRecomItems");
			$re["status"] = $RITEM->where("`num_iid`=".$numiid." AND `sid`=".$this->sid)->delete();
			$this->ajaxReturn($re);
		}
		public function save_gift(){
			// 本版支持四种领奖方式:
			// 先领先得:first_getting  数据库代码：1
			// 先猜先得:first_guess  数据库代码：2
			// 概率抽奖:lottery  数据库代码：3
			// 订单兑奖:order_exchange  数据库代码：4
			$cffsText =  I("cffsText");//猜分方式
			$hqfsText =  I("hqfsText");//获奖方式，中文
			$giftText =  I("giftText");//奖品名称
			$qutyText =  I("qutyText");//奖品数量
			$cffs =  I("cffs");//猜分方式，即分差
			$giftid =  I("giftid");//奖品ID
			$gifttp =  I("gifttp");//奖品ID
			$hqfs =  I("hqfs");//获取方式略语，英文
			$jpgl =  I("jpgl");//奖品概率
			$cjcs =  I("cjcs");//抽奖次数
			$ddje =  I("ddje");//订单金额 
			$fksjks =  I("fksjks");// 订单付款开始时间
			$fksjjs =  I("fksjjs");// 订单付款结束时间
			$playerid =  I("playerid");// 订单付款结束时间
			$event_id = session("event_id");
			
			if(!$event_id){
				$error = "活动ID为空！请从头开始创建活动！";
			}
			if(!$giftid){
				$error = "奖品ID为空！请重新选择奖品！";
			}
			if($error){
				$reda["hasError"]=true;
				$reda["error"]="添加奖品失败,原因如下：".$error;
				$this->ajaxReturn($reda);
				die();
			}
			$data["sid"]=$this->sid;
			$data["event_player_id"]=$playerid;
			$data["event_id"]=$event_id;
			$data["gift_id"]=$giftid;
			$data["type"]=$gifttp;
			$data["quantity"]=$qutyText;
			$data["quantity_install"]=$qutyText;
			$data["score_diff"]=$cffs;
			$data["add_time"]=date("Y-m-d H:i:s");
			$kxdr_getway = C("KXDR_GETWAY");
			$data["get_type"]=$kxdr_getway[$hqfs]["id"];  //将猜分方式略语变更为ID
			$data["name"] = I("gift_name");
			$data["pic_url"] = I("pic_url");
			$data["advance"] = I("hqfs"); //获取方式
			switch($data["advance"]){
				case "lottery" : //概率获奖，把抽奖概率和抽奖次数封装在json内
					$data["probability"] = I("jpgl")*1000;
					$data["lottery_times"] = I("cjcs");
				break;
				// case "time-range":
					// $data["range_time_start"] = I("range_time_start");
					// $data["range_time_end"] = I("range_time_end");
					// $data["advance_quantity"] = I("advance_quantity");
				// break;
				// case "ev-minute" :
					// $data["every_minute"] = I("every_minute");
					// $data["advance_quantity"] = I("advance_quantity");
				// break;
				// case "ev-lotts":
					// $data["every_lotts"] = I("every_lotts");
					// $data["advance_quantity"] = I("advance_quantity");
				// break;
				case "order":
					$data["payment"] = I("payment");
					$data["pay_time_start"] = I("pay_time_start");
					$data["pay_time_end"] = I("pay_time_end");
					$data["order_items"] = I("order_items");
				break;
				case "jifen":
					$data["jifen"] = I("jifen");
				break;
				case "metal":
					$data["medal_id"] = I("medal_id");
					$data["medal_name"] = I("medal_name");
					$data["medal_pic"] = I("medal_pic");
					$data["medal_quant"] = I("medal_quant");
				break;
				case "collect":
					$data["collect_items"] = I("collect_items");
				break;
				case "addcart":
					$data["cart_items"] = I("cart_items");
				break;
				case "friend_show":
					$data["show_title"] = I("show_title");
					$data["show_content"] = I("show_content");
				break;
			}
			$data["rule_medal_id"] = I("rule_medalid");
			$data["rule_medal_name"] = I("rule_medal_name");
			$data["rule_medal_pic"] = I("rule_medal_pic");
			// switch($hqfs){
				// case "lottery" : //概率获奖，把抽奖概率和抽奖次数封装在json内
				// unset($json);
				// $json["lottery"]["jpgl"]=$jpgl;
				// $json["lottery"]["cjcs"]=$cjcs;
				// $data["getting_json"] = json_encode($json);
				// break;
				// case "order_exchange" : //订单兑换，把订单起始日期和订单金额限定封装在json内
				// unset($json);
				// $json["order_exchange"]["order_start_date"]=$fksjks;
				// $json["order_exchange"]["order_end_date"]=$fksjjs;
				// $json["order_exchange"]["payment"]=$ddje;
				// $data["getting_json"] = json_encode($json);
				// break;
			// }
			
			$EGFT = M("KxdrEventGifts");
			$event_gift_id = $EGFT->add($data);
			if($event_gift_id){
				session("event_gift_id",$event_gift_id);
				$GFT = M("Gifts");
				$GFT->where("`id`=".$giftid)->setDec("quantity",$qutyText);
				unset($reda);
				$reda["gid"]=$event_gift_id;
				$reda["hasError"]=false;
			}else{
				unset($reda);
				$reda["hasError"]=true;
				$reda["error"]="添加奖品失败".$EGFT->getDbError();
			}
			$this->ajaxReturn($reda);
		}
		public function del_gift(){
			$gift_id = I("gid");
			$EGFT = M("KxdrEventGifts");
			$g = current($EGFT->where("`id`=".$gift_id." AND `sid`=".$this->sid)->getField("id,gift_id,quantity"));
			$re = $EGFT->where("`id`=".$gift_id." AND `sid`=".$this->sid)->delete();
			if($re){
				$GFT = M("Gifts");
				$req = $GFT->where("`id`=".$g["gift_id"])->setInc("quantity",$g["quantity"]);  //恢复被删除的数量
			}
			$reda["hasError"] = !$re;
			$reda["quantity"]=$g["quantity"];
			$reda["req"]=$req;
			$reda["error"]="";
			$this->ajaxReturn($reda);
		}
		public function setcur(){
			$CFG = D("Shopadmin/ShopCfg");
			$CFG->curtool="kxdr";
			$CFG->sid = $this->sid;
			$CFG->taobao_user_id=$this->taobao_user_id;
			$CFG->usernick=$this->usernick;
			$CFG->sessionkey=session("access_token");
			$CFG->refresh_token=session("refresh_token");
			$data = $CFG->setcur();
			$this->ajaxReturn($data);
		}
		public function set_app_version(){
			$version = I("version");
			$data["version"]=$version;
			$TOOL = D("ToolView");
			$re = $TOOL->where("`status`.`sid`=".$this->sid." AND `templet_code`='kxdr'")->save($data);
			if($re){
				session("app_version",$version);
				$data["status"]=true;
			}else{
				$data["status"]=false;
				$data["hasError"]=true;
				$data["error"]="更换版本失败，请重新登录试试";
			}
			$this->ajaxReturn($data);
		}
		
		public function setmulti(){
			$eid = (int)I("eid");
			$myes = I("myes");
			$mno = I("mno");
			$mnyes = I("mnyes");
			$mnno = I("mnno");
			$data["id"]=$eid?$eid:session("event_id");
			$data["multi_yes"]=$myes<=1?$myes:$mnyes;
			$data["multi_no"]=$mno<=1?$mno:$mnno;
			session("multi_yes",$data["multi_yes"]);
			session("multi_no",$data["multi_no"]);
			$EV = M("KxdrEvents");
			$re = $EV->where("`id`=".$data["id"]." AND `sid`=".$this->sid)->save($data);
			// if($re){
				$data["status"]=true;
			// }else{
				// $data["status"]=false;
				// $data["hasError"]=true;
				// $data["error"]="更新活动信息失败";
			// }
			$this->ajaxReturn($data);
		}
}